import 'dart:convert';
import 'dart:io';

//获取 all_string.json 下的所有字段，设置到intl_en
void main(List<String> args) async {
  File file = File(
      "/Users/yaplekde/Development/flutter_projects/mobile-app/lib/l10n/intl_en.arb");
  final data = await file.readAsString();
  Map<String, dynamic> jsonMap = json.decode(data);
  File allString = File(
      "/Users/yaplekde/Development/flutter_projects/mobile-app/lib/l10n/all_string.json");
  String allStringData = await allString.readAsString();
  Map<String, dynamic> tempData = json.decode(allStringData);
  tempData.forEach((key, value) {
    if (!jsonMap.containsValue(key)) {
      jsonMap[formatKey(key)] = value;
    }
  });

  File resultFile = File(
      "/Users/yaplekde/Development/flutter_projects/mobile-app/lib/l10n/intl_en_test.arb");
  if (resultFile.existsSync()) {
    await resultFile.create();
  }
  await resultFile.writeAsString(
      JsonEncoder.withIndent(" ").convert(jsonMap).replaceAll('\\n', r'\n'));
  print('done.');
  exit(0);
}

bool isUpperCase(int c) => c >= 65 && c <= 90;

String formatKey(String name) {
  final codeList = name.codeUnits;
  var result = <int>[];
  for (var i = 0; i < codeList.length; i++) {
    final code = codeList[i];
    if (String.fromCharCode(code) == ' ') {
      result.addAll('_'.codeUnits);
    } else {
      result.addAll(String.fromCharCode(code).toLowerCase().codeUnits);
    }
  }
  return String.fromCharCodes(result)
      .replaceAll('\\n', '_')
      .replaceAllMapped(RegExp("\n(\w+)\n"), (match) {
    for (var i = 0; i < match.groupCount; i++) {
      print('${match[i]}');
    }
    return '_${match[1]}';
  });
}
